<template>
  <div class="heatmap">
    <div class="heatmap-top">
      <p class="isred">{{$t('report.imReportDelistingNotice')}}</p>
      <el-form :inline="true" :model="formDate" :rules="rules" ref="ruleForm" :label-position="labelPosition" class="demo-form-inline">
        <el-form-item :label="$t('report.imReportLookTime')" prop="date">
          <el-date-picker
            v-model="formDate.date"
            type="daterange"
            :id="'report_date' + Math.random()"
            align="right"
            :clearable="false"
            @change="changeDate"
            size="mini"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('report.imReportpage')" prop="url">
          <el-select v-model="formDate.url" :placeholder="$t('report.imReportChoosePage')">
            <el-option v-for="(item, index) in clickUrl" :label="item._id" :value="item._id" :key="item._id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('report.webType')" class="questionToolTip">
          <el-radio-group v-model="formDate.resource">
            <el-radio label="1">{{$t('report.commonWeb')}}</el-radio>
            <el-radio label="2">{{$t('report.fullPageWeb')}}</el-radio>
          </el-radio-group>
          <el-tooltip class="item" effect="dark" popper-class="reportTip">
            <div slot="content">
              {{$t('report.heatmapTips1')}}<br>
              {{$t('report.heatmapTips2')}}<br>
              {{$t('report.heatmapTips3')}}<br>
              {{$t('report.heatmapTips4')}}<br>
              {{$t('report.heatmapTips5')}}<br>
              {{$t('report.heatmapTips6')}}<br>
            </div>
            <span class="tip"><i class="iconfont icon-tixingweizhi"></i></span>
          </el-tooltip>
        </el-form-item>
        <!--<el-form-item :label="'测试专用'" prop="userId">-->
          <!--<el-input type="text" placeholder="请输入userId" v-model="testUserId"></el-input>-->
        <!--</el-form-item>-->
        <el-button class="fr primary_btn" type="primary" @click="onSubmit('ruleForm')">{{$t('public.search2')}}</el-button>
      </el-form>
    </div>
    <div class="heatmap-top">
      <affix :label="$t('report.imReportVisitorHeatmapSearch')"></affix>
    </div>
    <div class="heatmapWarp">
        <div id="heatmapMask"></div>
        <iframe id="iframeId" :src="iframeSrc" name="mainweb" width="100%" scrolling="no" frameborder="no" sandbox="allow-scripts allow-forms allow-same-origin"></iframe>
      </div>
  </div>
</template>
<script>
  import h337 from 'heatmap.js'
  import {getDateTime, deepClone} from '@/utils/m7Utils'
  import affix from '../../../ui-modules/affix/Affix.vue'
  export default {
    name: 'imReportVisitorHeatmap',
    data () {
      return {
        rules: {
          url: [
            { required: true, message: this.$t('report.imReportChoosePage'), trigger: 'change' }
          ]
        },
        formDate: {
          resource: '1',
          url: '',
          date: [new Date(new Date() - 7 * 86400000), new Date(new Date() - 86400000)]
//          date: [new Date(), new Date()]
        },
        labelPosition: 'top',
        pickerOptions: {
          disabledDate (time) {
            if (time) {
              return time.getTime() + 86400000 > Date.now()
//              return time.getTime() > Date.now()
            }
          },
          shortcuts: [{
            text: this.$t('sms.thisOneWeek'),
            onClick (picker) {
              const end = new Date(new Date() - 86400000)
//              const end = new Date(new Date())
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: this.$t('sms.thisOneMonth'),
            onClick (picker) {
              const end = new Date(new Date() - 86400000)
//              const end = new Date(new Date())
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: this.$t('sms.thisThreeMonth'),
            onClick (picker) {
              const end = new Date(new Date() - 86400000)
//              const end = new Date(new Date())
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        iframeSrc: '',
        clickUrl: [],
        heatMapCoordinate: [],
        userId: '',
        testUserId: '' // 测试专用
      }
    },
    components: {
      affix
    },
    computed: {},
    watch: {
    },
    methods: {
      onSubmit (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.getClickMap()
          } else {
            return false
          }
        })
      },
      changeDate () {
        this.formDate.url = ''
        let data = {
          beginDate: getDateTime(this.formDate.date[0]).split(' ')[0],
          endDate: getDateTime(this.formDate.date[1]).split(' ')[0]
        }
        data.userId = this.userId ? this.userId : ''
        this.$store.dispatch('getClackHeatmap', data).then((data) => {
          if (data && data.length) {
            this.clickUrl = data
          } else {
            this.clickUrl = []
            this.$message.error(this.$t('report.imReportNoHeatMap'))
          }
        })
      },
      getClickMap () {
        this.heatMapCoordinate = []
        let data = {
          beginDate: getDateTime(this.formDate.date[0]).split(' ')[0],
          endDate: getDateTime(this.formDate.date[1]).split(' ')[0],
          url: encodeURIComponent(this.formDate.url)
        }
        let heatmapMask = document.getElementById('heatmapMask')
        let iframeId = document.getElementById('iframeId')
        let heatmapWarp = document.getElementsByClassName('heatmapWarp')[0]
        let pageScrollArr = this.clickUrl.filter((item) => item._id === this.formDate.url)[0].pageScrollHeight.toString().split('_')
        let pageScrollHeight = ''
        if (this.formDate.resource === '1') {
          pageScrollHeight = pageScrollArr[0] || ''
        } else {
          pageScrollHeight = pageScrollArr[1] || '600'
        }
        iframeId.height = pageScrollHeight
        heatmapMask.style.height = pageScrollHeight + 'px'
        heatmapWarp.style.height = pageScrollHeight + 'px'
        this.iframeSrc = this.formDate.url
        let currentWidth = document.getElementById('heatmapMask').clientWidth
        this.$store.dispatch('getClackHeatmap', data).then((data) => {
          this.heatMapCoordinate = data
          let dataJsonClone = []
          dataJsonClone = deepClone(this.heatMapCoordinate) || []
          if (dataJsonClone && dataJsonClone.length) {
            dataJsonClone.forEach((item, index) => {
              item.x = item.x + (currentWidth - 1600) / 2
              item.value = item.v
            })
            this.frames = dataJsonClone
            setTimeout(() => {
              if (heatmapMask && heatmapMask.firstChild) {
                let childs = heatmapMask.childNodes
                for (let i = childs.length - 1; i >= 0; i--) {
                  heatmapMask.removeChild(childs.item(i))
                }
              }
              let heatmapInstance = h337.create({
                container: document.getElementById('heatmapMask'),
                radius: 50,
                maxOpacity: 0.9,
                minOpacity: 0.5,
                blur: 0.75,
                max: 5
              })
              console.log(dataJsonClone)
//              let dataObj = {}
//              dataObj.data = dataJsonClone
//              heatmapInstance.setData(dataObj)
              this.frames.forEach((frame) => {
                if (frame.x < 0 || frame.x > currentWidth) {
                  console.log('frame.x', frame.x)
                  return
                }
                heatmapInstance.addData({
                  x: Math.floor(frame.x),
                  y: Math.floor(frame.y),
                  value: frame.v
                })
              })
            }, 500)
          }
        })
      }
    },
    mounted () {
      let data = {
        beginDate: getDateTime(this.formDate.date[0]).split(' ')[0],
        endDate: getDateTime(this.formDate.date[1]).split(' ')[0]
      }
      this.$store.dispatch('getCache', {type: 'clackUserId'}).then(res => {
        this.userId = res.userId
        data.userId = this.userId ? this.userId : ''
        this.$store.dispatch('getClackHeatmap', data).then((data) => {
          this.clickUrl = data
        })
      })
    },
    beforeMount () {
  //      this.getClickMap()
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .heatmap
    margin-bottom: -20px
    position relative
  .heatmapWarp
    margin-top: 25px
  #heatmapMask
    width 100%
    background-color $cf-gray0
    opacity 0.3
    min-width: 1200px
    position: absolute !important
    z-index: 11
  #iframeId
    min-width 1200px
  .isred
    margin-bottom 10px
    color $c-pink
  .el-form
    margin 0px 0 0 18px
    .primary_btn
      margin-top 14px
    .el-form-item
      vertical-align top
  .tipContent
    font-size: 12px
    margin-left: 10px
  .questionToolTip
    .tip
      cursor pointer
      display inline-block
      height 16px
      width 16px
      border 1px solid $c-main
      text-align center
      line-height 16px
      border-radius 50%
      margin-left 2px
      .iconfont
        font-size 10px
        color $c-main
        border none
  .heatmap-top
    padding: 20px 30px 0 20px
</style>
